package com.batchengine.service;

import com.batchengine.system.SystemMemoryInfo;
import com.batchengine.util.ControlPortHelper;
import static com.batchengine.util.ControlPortHelper.*;
import static com.batchengine.util.EnvUtil.getHTMLFolderLocation;
import static com.batchengine.velocity.VelocityEngine.getVelocityFormattedData;
import static com.batchengine.velocity.VelocityEngine.reDirectPage;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.*;
import static java.lang.String.format;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * User: sunilkalva
 * Date: Jul 16, 2009
 */
public class BatchEngineHttpHandler implements HttpHandler {

    private static final String index = getHTMLFolderLocation() + "index.html";

    public void handle(HttpExchange exchange) throws IOException {

        String requestMethod = exchange.getRequestMethod();
        if (requestMethod.equalsIgnoreCase("GET")) {

            String args[] = null;
            Map<String, String> paramMap = new HashMap<String, String>();

            String path = exchange.getRequestURI().getPath();
            String query = exchange.getRequestURI().getRawQuery();
            if (null != query) {

                args = query.split("&");
                if (null != args && 0 < args.length) {
                    for (String arg : args) {

                        try {
                            paramMap.put(arg.split("=")[0], arg.split("=")[1]);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

            OutputStream responseBody = getOutputStream(exchange);
            responseBody.write("<html><body>".getBytes());
            PrintWriter writer = new PrintWriter(responseBody);

            path = path.replaceAll("//", "/");
            if ("/bash".equalsIgnoreCase(path) || "/bash/".equalsIgnoreCase(path)) {

                try {

                    InputStream indexFile = new FileInputStream(index);
                    int data = 0;
                    while ((data = indexFile.read()) != -1) {
                        responseBody.write(data);
                    }
                    responseBody.flush();
                    responseBody.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if ("/bash/headers".equalsIgnoreCase(path)) {

                Headers requestHeaders = exchange.getRequestHeaders();
                Set<String> keySet = requestHeaders.keySet();
                for (String aKeySet : keySet) {
                    List<String> values = requestHeaders.get(aKeySet);
                    String s = aKeySet + " = " + values.toString() + "\n";
                    responseBody.write(s.getBytes());
                }
                responseBody.close();
            } else if ("/bash/showHealth".equalsIgnoreCase(path)) {

                SystemMemoryInfo systemMemoryInfo = SystemMemoryInfo.getSystemMemoryInfo();
                Map<String, Object> memory = new HashMap<String, Object>();
                memory.put("health", systemMemoryInfo);
                String data = getVelocityFormattedData("SystemHealth.vm", memory);
                writer.write(data);
                writer.flush();
                responseBody.close();
            } else if ("/bash/shutdown".equalsIgnoreCase(path)) {

                String msg = "Successfully stopped BasgEngine .................!!!!!";
                responseBody.write(msg.getBytes());
                responseBody.flush();
                responseBody.close();
                System.exit(1);
            } else if ("/bash/DisplayUserManagers".equalsIgnoreCase(path)) {

                ControlPortHelper.displayUserManagers(writer, true);
                writer.flush();
                responseBody.close();
            } else if ("/bash/DisplayManager".equalsIgnoreCase(path)) {

                displayManager(writer, paramMap.get("managerId"), true);
                writer.flush();
                responseBody.close();
            } else if ("/bash/DisplayPool".equalsIgnoreCase(path)) {

                displayPool(writer, paramMap.get("managerId"), paramMap.get("poolId"), true);
                writer.flush();
                responseBody.close();
            } else if ("/bash/killPool".equalsIgnoreCase(path)) {

                killPool(writer, paramMap.get("managerId"), paramMap.get("poolId"), true);
                String s = reDirectPage(format("/bash/DisplayManager?managerId=%s", paramMap.get("managerId")));
                writer.print(s);
                writer.flush();
                responseBody.close();
            } else if ("/bash/restartPool".equalsIgnoreCase(path)) {

                restartPool(writer, paramMap.get("managerId"), paramMap.get("poolId"), true);
                String s = reDirectPage(format("/bash/DisplayManager?managerId=%s", paramMap.get("managerId")));
                writer.print(s);
                writer.flush();
                responseBody.close();
            } else if ("/bash/pauseWorker".equalsIgnoreCase(path)) {

                pauseWorker(writer, paramMap.get("managerId"), paramMap.get("poolId"), paramMap.get("workerId"), paramMap.get("type"), true);
                String s = reDirectPage(format("displayPool?managerId=%s&poolId=%s", paramMap.get("managerId"),paramMap.get("poolId")));
                writer.print(s);
                writer.flush();
                responseBody.close();
            } else if ("/bash/resumeWorker".equalsIgnoreCase(path)) {

                resumeWorker(writer, paramMap.get("managerId"), paramMap.get("poolId"), paramMap.get("workerId"), paramMap.get("type"), true);
                String s = reDirectPage(format("displayPool?managerId=%s&poolId=%s", paramMap.get("managerId"),paramMap.get("poolId")));
                writer.print(s);
                writer.flush();
                responseBody.close();
            } else if ("/bash/cancelScheduledTask".equalsIgnoreCase(path)) {

                cancelScheduledTask(Long.parseLong(paramMap.get("cronId")));
                String s = reDirectPage(format("/bash/DisplayManager?managerId=%s", paramMap.get("managerId")));
                writer.print(s);
                writer.flush();
                responseBody.close();
            }
            responseBody.write("</html></body>".getBytes());
        }
    }

    private OutputStream getOutputStream(HttpExchange exchange) throws IOException {

        OutputStream responseBody = exchange.getResponseBody();
        Headers responseHeaders = exchange.getResponseHeaders();
        responseHeaders.set("Content-Type", "text/html");
        exchange.sendResponseHeaders(200, 0);
        return responseBody;
    }

}